const fs = require('fs');
const { MongoClient } = require('mongodb');
const path = require('path');

const folderPath = 'D:/Users/liuhuanjie/Desktop/1'; // 文件夹路径
const mongoURI = 'mongodb://localhost:27017'; // MongoDB数据库连接URI
const dbName = 'forge'; // 数据库名称

// 连接到MongoDB数据库
MongoClient.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }, async (err, client) => {
  if (err) {
    console.error('Error connecting to MongoDB:', err);
    return;
  }
  console.log('Connected to MongoDB successfully.');

  try {
    const db = client.db(dbName);

    // 读取文件夹下所有文件名
    const files = await fs.promises.readdir(folderPath);

    // 遍历文件名数组
    for (const file of files) {
      const filePath = path.join(folderPath, file);
      // 仅处理 JSON 文件
      if (file.endsWith('.json')) {
        console.log('Processing file:', filePath);
        const collectionName = path.basename(file, '.json'); // 获取集合名称
        await importJSONToMongo(db, filePath, collectionName); // 导入数据到MongoDB
      }
    }

    console.log('All files imported to MongoDB successfully.');
  } catch (err) {
    console.error('Error importing files to MongoDB:', err);
  } finally {
    // 关闭MongoDB连接
    client.close();
  }
});

// 导入JSON数据到MongoDB集合
async function importJSONToMongo(db, filePath, collectionName) {
  const data = await fs.promises.readFile(filePath, 'utf8');
  const jsonData = JSON.parse(data);
  const collection = db.collection(collectionName);
  await collection.insertMany(jsonData);
  console.log('Data imported to collection:', collectionName);
}
